package com.hongtech.tiny.modules.oss.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongtech.tiny.common.exception.CustomException;
import com.hongtech.tiny.common.response.PageResult;
import com.hongtech.tiny.modules.oss.config.FileProperties;
import com.hongtech.tiny.modules.oss.entity.LocalFileEntity;
import com.hongtech.tiny.modules.oss.mapper.LocalFileMapper;
import com.hongtech.tiny.modules.oss.service.LocalFileService;
import com.hongtech.tiny.modules.oss.utils.FileUtils;
import com.hongtech.tiny.modules.oss.vo.LocalFileQueryCriteria;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class LocalFileServiceImpl extends ServiceImpl<LocalFileMapper, LocalFileEntity> implements LocalFileService {

    private final LocalFileMapper localFileMapper;

    private final FileProperties properties;

    @Override
    public PageResult<LocalFileEntity> queryAll(LocalFileQueryCriteria criteria, Page<LocalFileEntity> page){
        Page<LocalFileEntity> list = localFileMapper.findAll(criteria, page);
        return PageResult.restPage(list);
    }

    @Override
    public List<LocalFileEntity> queryAll(LocalFileQueryCriteria criteria){
        return localFileMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LocalFileEntity create(String name, MultipartFile multipartFile) {
        FileUtils.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtils.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtils.getFileType(suffix);
        String filePath = properties.getPath().getPath() + type +  File.separator;
        File file = FileUtils.upload(multipartFile, filePath);
        if(ObjectUtil.isNull(file)){
            throw new CustomException("上传失败");
        }
        try {
            name = StringUtils.isBlank(name) ? FileUtils.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            LocalFileEntity localFileEntity = new LocalFileEntity(
                    file.getName(),
                    name,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtils.getSize(multipartFile.getSize())
            );
            save(localFileEntity);
            return localFileEntity;
        }catch (Exception e){
            FileUtils.del(file);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(LocalFileEntity resources) {
        LocalFileEntity localFileEntity = getById(resources.getId());
        localFileEntity.copy(resources);
        saveOrUpdate(localFileEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            LocalFileEntity storage = getById(id);
            FileUtils.del(storage.getPath());
            removeById(storage);
        }
    }

    @Override
    public void download(List<LocalFileEntity> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LocalFileEntity localFileEntity : queryAll) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名", localFileEntity.getRealName());
            map.put("备注名", localFileEntity.getName());
            map.put("文件类型", localFileEntity.getType());
            map.put("文件大小", localFileEntity.getSize());
            map.put("创建日期", localFileEntity.getCreateTime());
            list.add(map);
        }
        FileUtils.downloadExcel(list, response);
    }
}
